import React, { useEffect, useState, useCallback, Fragment } from 'react';
import { connect } from 'umi';
import { history } from 'umi';
import { Form, Table } from 'antd';
import { eventTrack } from '@/utils/track';
import { Pagination } from '@/components';
import moment from 'moment';
import LinkTo from '@/components/LinkTo';
import { getTempDetail } from '@/services/myRecruit/talentPool';
import styles from './TerviewList.less';
import SearchForm from './Components/SearchForm';
import SendMail from './Components/SendMail';
import CancelInterview from './Components/CancelInterview';

const LaunchInterview = ({ dispatch, form, interview, user, name, loading }) => {
    const { pagination, orderBy, querymyinterviewsList, interviewTypeList, interviewConclusionTypeList } = interview;
    const [interviewTypeValue, setinterviewTypeValue] = useState([]);
    const [interviewConclusionValue, setinterviewConclusionValue] = useState([]);
    const [tempInfo, setTempInfo] = React.useState({}); // 控制邮件模板类型
    const [mailModle, setMailModle] = React.useState(); // 控制发送候选人邮件模态框
    const [cancelInfo, setCancelInfo] = React.useState();
    const [cancelInterview, setCancelInterview] = React.useState(false);
    const [sorters, setSorters] = useState(''); // 排序储存
    const [filter, setFilter] = useState({}); // 排序储存

    const User = user.currentUser; // 登陆人信息
    const handleOpenMile = useCallback(async record => {
        const res = await getTempDetail({
            interviewArrangeCode: record.interviewArrangeCode,
            talentCode: record.talentCode
        });
        setTempInfo({ ...res.data, talentCode: record.talentCode, talentEmail: record.talentEmail, key: res.data.key });
        setMailModle(true);
    }, []);
    // 表格操作返回项
    const actionReturn = record => {
        if (record.isEditArrange) {
            return (
                <Fragment>
                    <LinkTo
                        onClick={async (e, url) => {
                            // 埋点
                            await eventTrack({
                                eventName: 'personal_my_recruit_interview_operator_click',
                                eventProps: {
                                    tabs: '我发起的面试',
                                    label: '我的面试-操作-修改面试'
                                }
                            });
                            history.push(url);
                        }}
                        to="/personal/portal/recruit/interview/edit"
                        query={{
                            arrangeCode: record.interviewArrangeCode,
                            code: record.candidateCode,
                            type: 'type1'
                        }}
                    >
                        修改面试
                    </LinkTo>
                    <a
                        style={{ display: ' block' }}
                        onClick={async (e, url) => {
                            e.preventDefault();
                            setCancelInfo({
                                candidateCode: record.candidateCode,
                                interviewArrangeCode: record.interviewArrangeCode,
                                interviewEmployeeCode: record.interviewEmployeeCode,
                                interviewEmployeeName: record.interviewEmployeeName,
                                interviewRecordCode: record.interviewRecordCode,
                                interviewTime: record.interviewTime,
                                interviewTypeValue: record.interviewTypeValue,
                                talentName: record.talentName
                            });
                            await eventTrack({
                                eventName: 'personal_my_recruit_interview_operator_click',
                                eventProps: {
                                    tabs: '我发起的面试',
                                    label: '我的面试-操作-取消面试'
                                }
                            });
                            history.push(url);
                            setCancelInterview(true);
                            // handleOpenMile(record);
                        }}
                    >
                        取消面试
                    </a>
                    <a
                        onClick={e => {
                            e.preventDefault();
                            handleOpenMile(record);
                            eventTrack({
                                eventName: 'personal_my_recruit_interview_operator_click',
                                eventProps: {
                                    tabs: '我发起的面试',
                                    label: '我的面试-操作-通知候选人'
                                }
                            });
                            // setMailModle(true);
                        }}
                    >
                        通知候选人
                    </a>
                </Fragment>
            );
        }

        return (
            <LinkTo
                onClick={async (e, url) => {
                    // 埋点
                    await eventTrack({
                        eventName: 'personal_my_recruit_interview_operator_click',
                        eventProps: {
                            tabs: '我发起的面试',
                            label: '我的面试-操作-面试详情'
                        }
                    });
                    history.push(url);
                }}
                to="/personal/portal/recruit/interview/edit"
                query={{
                    arrangeCode: record.interviewArrangeCode,
                    code: record.candidateCode,
                    type: 'type3'
                }}
            >
                面试详情
            </LinkTo>
        );
    };
    const getSexName = key => {
        if (key === '1') {
            return (
                <i className="iconfont iconoa_table_icon_men_default" style={{ color: '#3aa0ff', margin: '0 5px' }} />
            );
        }
        if (key === '2') {
            return (
                <i className="iconfont iconoa_table_icon_women_default" style={{ color: '#f2637b', margin: '0 5px' }} />
            );
        }
        return '';
    };
    const getName = list => (
        <Fragment>
            <div className={styles.colum_info_1}>
                <div
                    title={list.talentName}
                    style={{
                        display: 'inline-block',
                        maxWidth: '200px',
                        overflow: 'hidden',
                        textOverflow: 'ellipsis',
                        whiteSpace: 'nowrap',
                        verticalAlign: ' text-bottom'
                    }}
                >
                    <LinkTo
                        onClick={async (e, url) => {
                            // 埋点
                            await eventTrack({
                                eventName: 'personal_my_recruit_interview_detail_click',
                                eventProps: {
                                    tabs: '我发起的面试',
                                    label: '我的面试-面试详情'
                                }
                            });
                            history.push(url);
                        }}
                        className={styles.LinkTo}
                        to="/personal/portal/recruit/interview/edit"
                        query={{
                            arrangeCode: list.interviewArrangeCode,
                            code: list.candidateCode,
                            type: 'type3'
                        }}
                    >
                        {list.talentName}
                    </LinkTo>
                </div>
                {getSexName(list.talentSex)}
            </div>
        </Fragment>
    );
    const columns = [
        {
            title: '姓名',
            dataIndex: 'talentName',
            key: 'talentName',
            width: 160,
            fixed: 'left',
            render: (text, record) => getName(record)
        },
        {
            title: '应聘职位',
            dataIndex: 'recruitPost',
            fixed: 'left',
            key: 'recruitPost',
            width: 160
        },
        {
            title: '公司',
            dataIndex: 'companyName',
            key: 'companyName',
            width: 200
        },
        {
            title: '面试时间',
            dataIndex: 'interviewTime',
            key: 'interviewTime',
            sorter: () => {},
            width: 200
        },
        {
            title: '面试类型',
            dataIndex: 'interviewTypeValue',
            key: 'interviewTypeValue',
            filters: interviewTypeList,
            width: 180
        },
        {
            title: '面试结果',
            dataIndex: 'interviewConclusionValue',
            key: 'interviewConclusionValue',
            filters: interviewConclusionTypeList,
            width: 180
        },
        {
            title: '评分',
            dataIndex: 'interviewScore',
            key: 'interviewScore',
            sorter: () => {},
            width: 120,
            render: text => {
                if (text || text === 0) {
                    return `${text} 分`;
                }
                return '--';
            }
        },
        {
            title: '面试官',
            dataIndex: 'interviewEmployeeName',
            key: 'interviewEmployeeName'
            // width: 140
        },
        {
            title: '操作',
            dataIndex: 'action',
            key: 'action',
            render: (text, record) => actionReturn(record),
            width: 120,
            fixed: 'right'
        }
    ];

    const getListDict = () => {
        dispatch({
            type: 'interview/getListDict'
        });
    };
    const changeTable = (paginations, filters, sorter) => {
        let orderBys;
        let sorterField;
        if (sorter && sorter.field && sorter.order) {
            if (sorter.field === 'interviewTime') {
                sorterField = 'interview_time';
            }
            if (sorter.field === 'interviewScore') {
                sorterField = 'interview_score';
            }
            const order = sorter.order.trim().split('end')[0];
            orderBys = `${sorterField} ${order}`;
        } else if (typeof sorters === 'string') {
            dispatch({
                type: 'interview/save',
                payload: {
                    orderBy: ''
                }
            });
        }

        if (filters && filters.interviewTypeValue) {
            setinterviewTypeValue(filters.interviewTypeValue);
        }
        if (filters && filters.interviewConclusionValue) {
            setinterviewConclusionValue(filters.interviewConclusionValue);
        }
        dispatch({
            type: 'interview/save',
            payload: {
                orderBy: orderBys || '',
                pagination: {
                    ...interview.pagination,
                    ...paginations
                }
            }
        });
        // 新的分页组件无法自动回到第一页的bug修复
        if (sorter && sorters !== sorter) {
            setSorters(sorter);
            dispatch({
                type: 'interview/save',
                payload: {
                    orderBy: orderBys || '',
                    pagination: {
                        ...interview.pagination,
                        current: 1
                    }
                }
            });
        }
        if (filters && JSON.stringify(filter) !== JSON.stringify(filters)) {
            setFilter(filters);
            dispatch({
                type: 'interview/save',
                payload: {
                    orderBy: orderBys || '',
                    pagination: {
                        ...interview.pagination,
                        current: 1
                    }
                }
            });
        }
    };
    const getPayload = type => {
        const {
            candidateName,
            insertDate,
            companyId,
            interviewEmployeeId,
            interviewLeaderId,
            recruitCode
        } = form.getFieldsValue();
        const payload = {
            candidateName: candidateName || '',
            companyId: companyId || '',
            beginTime: insertDate && insertDate.length > 0 ? moment(insertDate[0]).format('YYYY-MM-DD 00:00:00') : '',
            endTime: insertDate && insertDate.length > 0 ? moment(insertDate[1]).format('YYYY-MM-DD 23:59:59') : '',
            interviewEmployeeCodes: interviewEmployeeId || [],
            interviewLeaderIds: interviewLeaderId || [],
            recruitCode: recruitCode || '',
            interviewType: interviewTypeValue,
            interviewConclusion: interviewConclusionValue,

            orderByField: orderBy,
            pageNo: type ? 1 : pagination.current,
            pageSize: type ? 10 : pagination.pageSize
        };
        return payload;
    };
    // 高级搜索
    const handleSearch = type => {
        dispatch({
            type: 'interview/querymyinterviews',
            payload: getPayload(type)
        });
    };

    useEffect(
        () => () => {
            dispatch({
                type: 'interview/save',
                payload: {
                    orderBy: '',
                    pagination: {
                        ...pagination,
                        pageSize: 10,
                        current: 1
                    }
                }
            });
        },
        []
    );

    useEffect(() => {
        getListDict();
    }, []);
    useEffect(() => {
        if (name) {
            form.setFieldsValue(
                {
                    candidateName: name
                },
                () => {
                    handleSearch();
                }
            );
        } else {
            handleSearch();
        }
    }, [pagination.pageSize, pagination.current, orderBy, interviewConclusionValue, interviewTypeValue]);

    return (
        <Fragment>
            <SearchForm
                form={form}
                user={User}
                onSearch={e => {
                    // 埋点;
                    const { eType } = e;
                    handleSearch(1);
                    eventTrack({
                        eventName:
                            eType === 'submit'
                                ? 'personal_my_recruit_interview_search_click'
                                : 'personal_my_recruit_interview_reset_click',
                        eventProps: {
                            tabs: '我发起的面试',
                            keyword: eType === 'submit' ? JSON.stringify(form.getFieldsValue()) : null
                        }
                    });
                }}
                identity="apply"
            />
            <Table
                bordered={false}
                loading={loading.effects['interview/querymyinterviews']}
                dataSource={querymyinterviewsList}
                columns={columns}
                scroll={{ x: 'max-content' }}
                onChange={changeTable}
                rowKey="id"
                pagination={false}
            />
            <Pagination {...pagination} onChange={changeTable} />
            <CancelInterview
                visible={cancelInterview}
                setVisible={setCancelInterview}
                data={{ cancelInfo, handleSearch }}
                onCancel={() => {
                    setCancelInterview(false);
                }}
            />
            <SendMail
                form={form}
                visible={mailModle}
                setMailModle={setMailModle}
                data={{ tempInfo }}
                onCancel={() => {
                    setMailModle(false);
                }}
            />
        </Fragment>
    );
};

export default connect(({ loading, interview, user }) => ({
    user,
    interview,
    loading
}))(Form.create()(LaunchInterview));
